#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
真实数据获取测试脚本
验证是否能够成功获取网络真实数据
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from real_data_fetcher import RealDataFetcher
import pandas as pd

def test_real_data_fetching():
    """测试真实数据获取"""
    print("🌐 真实数据获取测试")
    print("="*60)
    
    # 测试股票列表
    test_stocks = [
        "000001",  # 平安银行
        "000002",  # 万科A  
        "600036",  # 招商银行
        "600519",  # 贵州茅台
        "000858"   # 五粮液
    ]
    
    fetcher = RealDataFetcher()
    
    print("🎯 测试目标: 确保所有数据都来自网络真实数据源")
    print("📊 测试股票:", ", ".join(test_stocks))
    print()
    
    success_count = 0
    fail_count = 0
    
    for i, stock_code in enumerate(test_stocks, 1):
        print(f"📈 [{i}/{len(test_stocks)}] 测试股票: {stock_code}")
        print("-" * 40)
        
        # 获取历史数据
        data = fetcher.get_stock_data(stock_code, 5)
        
        if not data.empty:
            print(f"✅ 成功获取数据")
            print(f"📊 数据详情:")
            print(f"   • 记录数: {len(data)} 条")
            print(f"   • 列数: {len(data.columns)}")
            print(f"   • 列名: {list(data.columns)}")
            print(f"   • 最新收盘价: {data['close'].iloc[-1]:.2f}元")
            print(f"   • 日期范围: {data.index.min().date()} 到 {data.index.max().date()}")
            
            # 检查价格合理性
            latest_price = data['close'].iloc[-1]
            if 1 <= latest_price <= 1000:  # 合理价格范围
                print(f"✅ 价格数据合理")
                success_count += 1
            else:
                print(f"⚠️ 价格数据可能不合理: {latest_price}")
                
        else:
            print(f"❌ 获取数据失败")
            fail_count += 1
            
        print()
    
    print("="*60)
    print("🎯 测试结果统计:")
    print(f"✅ 成功: {success_count}/{len(test_stocks)} 只股票")
    print(f"❌ 失败: {fail_count}/{len(test_stocks)} 只股票")
    print(f"📊 成功率: {success_count/len(test_stocks)*100:.1f}%")
    
    if success_count == len(test_stocks):
        print("\n🎉 所有股票都成功获取真实数据！")
        return True
    elif success_count > 0:
        print(f"\n⚠️ 部分股票获取成功，建议检查失败股票的代码或网络")
        return False
    else:
        print(f"\n❌ 所有股票都获取失败，请检查:")
        print(f"   • 网络连接是否正常")
        print(f"   • akshare是否正常工作")
        print(f"   • 是否需要安装备用数据源")
        return False

def test_data_consistency():
    """测试数据一致性（使用真实数据）"""
    print("\n🔄 真实数据一致性测试")
    print("="*60)
    
    test_stock = "000001"
    print(f"📊 测试股票: {test_stock}")
    
    # 多次获取同一股票数据
    prices = []
    for i in range(3):
        fetcher = RealDataFetcher()
        data = fetcher.get_stock_data(test_stock, 5)
        
        if not data.empty:
            price = data['close'].iloc[-1]
            prices.append(price)
            print(f"第{i+1}次获取: {price:.2f}元")
        else:
            print(f"第{i+1}次获取: 失败")
            
    if len(prices) >= 2:
        is_consistent = len(set(prices)) == 1
        print(f"\n📊 一致性结果: {'✅ 一致' if is_consistent else '❌ 不一致'}")
        
        if not is_consistent:
            max_price = max(prices)
            min_price = min(prices)
            diff_pct = (max_price - min_price) / min_price * 100
            print(f"⚠️ 价格差异: {diff_pct:.3f}%")
            print(f"💡 注意: 股票价格可能在获取过程中发生实时变化")
            
        return is_consistent
    else:
        print("❌ 无法进行一致性测试，数据获取失败")
        return False

def check_data_sources():
    """检查可用的数据源"""
    print("\n🔧 数据源检查")
    print("="*60)
    
    # 检查akshare
    try:
        import akshare as ak
        print("✅ akshare 已安装")
        
        # 简单测试
        try:
            stock_list = ak.stock_zh_a_spot_em()
            if not stock_list.empty:
                print(f"✅ akshare 运行正常，获取到 {len(stock_list)} 只股票")
            else:
                print("⚠️ akshare 返回空数据")
        except Exception as e:
            print(f"❌ akshare 测试失败: {e}")
            
    except ImportError:
        print("❌ akshare 未安装")
        print("💡 安装命令: pip install akshare")
    
    # 检查yfinance
    try:
        import yfinance as yf
        print("✅ yfinance 已安装")
    except ImportError:
        print("⚠️ yfinance 未安装（备用数据源）")
        print("💡 安装命令: pip install yfinance")
    
    # 检查tushare
    try:
        import tushare as ts
        print("✅ tushare 已安装")
    except ImportError:
        print("⚠️ tushare 未安装（备用数据源）")
        print("💡 安装命令: pip install tushare")

if __name__ == "__main__":
    print("🚀 开始真实数据获取测试...")
    
    # 检查数据源
    check_data_sources()
    
    # 测试真实数据获取
    success = test_real_data_fetching()
    
    # 测试数据一致性
    if success:
        test_data_consistency()
    
    print("\n" + "="*60)
    print("🎯 测试完成！")
    
    if success:
        print("✅ 系统现在只使用真实网络数据")
        print("🔒 模拟数据生成已禁用")
    else:
        print("❌ 真实数据获取存在问题，需要修复")
        print("💡 请根据上述提示进行调整")
